<?php

namespace App\Admin\Controllers;

use App\Admin\Renderable\SpeakerCollectionTable;
use App\Admin\Renderable\SpeakerTable;
use App\Admin\Repositories\ForeignSpeakerCollection;
use App\Models\ForeignSpeaker;
use App\Models\ForeignSpeakerCollection as AppForeignSpeakerCollection;
use App\Models\ForeignSpeakerCollectionPivot;
use App\Models\Member;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AdminController;
use Carbon\Carbon;
use Illuminate\Support\Arr;

class ForeignSpeakerCollectionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ForeignSpeakerCollection(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->disableActions();
            $grid->disableCreateButton();
            $grid->column('name')->expand(function () {
                return SpeakerCollectionTable::make(['id' => $this->id]);
            });
            $grid->column('photo');
            $grid->column('sort');
            $grid->column('status')->switch();
            // $grid->column('is_del');
            $grid->column('user_id')->display(function ($id) {
                return User::find($id)->realname ?? '暂无';
            });;
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            /**
             * 按钮控制.
             */
            // @permissions
            if (!Admin::user()->can('speaker-collection-create')) {
                $grid->disableCreateButton();
                // $grid->disableQuickCreateButton();
            }
            // @permissions
            if (!Admin::user()->can('speaker-collection-update')) {
                $grid->disableEditButton();
                // $grid->disableQuickEditButton();
            }
            // @permissions
            if (!Admin::user()->can('speaker-collection-delete')) {
                $grid->disableDeleteButton();
            }
            // @permissions
            // if (Admin::user()->can('speaker-collection-share')) {
            //     $grid->actions([new ShareCollection()]);
            // }
            $grid->filter(function (Grid\Filter $filter) {
                // $filter->equal('id');
                $filter->like('name');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ForeignSpeakerCollection(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('photo');
            $show->field('sort');
            $show->field('status')->using(['1' => '显示', '0' => '不显示']);;
            // $show->field('is_del');
            $show->field('user_id');
            $show->field('pivot_id', '外籍讲者')->as(function ($ids) {
                return ForeignSpeaker::whereIn('id', explode(',', $ids))->pluck('name');
            })->label();
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $builder = AppForeignSpeakerCollection::with('guest_collection_pivot');
        return Form::make($builder, function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->image('photo')->autoUpload()->move('speakerCollection/photo/' . date('Y/m'));
            $form->text('sort');
            $form->radio('status')->options([1 => '显示', 0 => '不显示'])->default(1);
            // $form->checkbox('外籍讲者')->options($form->model()->guest_collection_pivot->pluck('name', 'id')->toArray());
            $form->multipleSelectTable('pivot_id', '选择专家')
                ->title('专家库')
                // ->max(4)
                ->from(SpeakerTable::make())
                ->model(ForeignSpeaker::class, 'id', 'name')
                ->saving(function ($value) {

                    return implode(',', $value);
                })->required();
            // $form->text('is_del');
            // $form->text('user_id');
            $form->hidden('status')
                ->customFormat(function ($v) {
                    return $v == 1 ? 1 : 0;
                })
                ->saving(function ($v) {
                    return $v ? '1' : '0';
                });
            // $form->display('created_at');
            // $form->display('updated_at');
            $form->saved(function (Form $form, $result) {

                if ($form->isCreating()) {

                    $pivot_ids = explode(',', $form->pivot_id);
                    $arr = Arr::crossJoin(collect($result), $pivot_ids);

                    $data = [];
                    foreach ($arr as $key => $val) {
                        $data['collection_id'] = $val[0];
                        $data['speaker_id'] = $val[1];
                        $data['created_at'] = Carbon::now()->toDateTimeString();
                        ForeignSpeakerCollectionPivot::create($data);
                    }
                }

                if ($form->isEditing()) {
                    $pivot_ids = explode(',', $form->model()->pivot_id);
                    ForeignSpeakerCollectionPivot::where('collection_id', $form->model()->id)->delete();
                    $arr = Arr::crossJoin(collect($form->model()->id), $pivot_ids);
                    $data = [];
                    foreach ($arr as $key => $val) {
                        $data['collection_id'] = $val[0];
                        $data['speaker_id'] = $val[1];
                        $data['created_at'] = Carbon::now()->toDateTimeString();
                        $data['updated_at'] = Carbon::now()->toDateTimeString();
                        ForeignSpeakerCollectionPivot::create($data);
                    }
                }
            });
        });
    }
}
